package main

import (
	"html/template"
	"io"
	"net/http"
	"os"

	"github.com/astaxie/beego"
)

const page = `
<!DOCTYPE html>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <div class="container">
        <form action="/attachment" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label>文件上传：</label>
                <input type="file" name="attachment" class="form-control">
            </div>
            <button type="submit">提交</button>
    </div>
    </form>
</body>
</html>
`

var files = []string{}

func main() {
	os.Mkdir("attachment", os.ModePerm)
	http.HandleFunc("/attachment", func(w http.ResponseWriter, r *http.Request) {
		beego.Info(r.Method)
		switch r.Method {
		case "POST":
			file, fh, err := r.FormFile("attachment")
			if err != nil {
				io.WriteString(w, err.Error())
				return
			}
			f, err := os.Create("attachment/" + fh.Filename)
			if err != nil {
				io.WriteString(w, err.Error())
				return
			}
			defer f.Close()
			_, err = io.Copy(f, file)
			if err != nil {
				io.WriteString(w, err.Error())
				return
			}
			files = append(files, fh.Filename)
		case "GET":
			// http://localhost/attachment?f=a.txt
			f, err := os.Open("attachment/" + r.URL.Query()["f"][0])
			if err != nil {
				io.WriteString(w, err.Error())
				return
			}
			defer f.Close()
			_, err = io.Copy(w, f)
			if err != nil {
				io.WriteString(w, err.Error())
				return
			}
		}
	})

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		t := template.New("attachment")
		t.Parse(page)
		t.Execute(w, nil)
	})
	http.ListenAndServe(":80", nil)
}
